package com.bird.user.adapter.database

import com.bird.component.database.*
import com.bird.component.lang.util.log
import com.bird.user.adapter.database.dataobj.UserDO
import com.bird.user.adapter.database.dataobj.UserRoleDO
import com.bird.user.adapter.database.mapper.UserMapper
import com.bird.user.adapter.database.mapper.UserRoleMapper
import com.bird.user.application.UserAppQueryRepository
import com.bird.user.domain.UserEntity
import com.bird.user.domain.UserRepository
import org.springframework.stereotype.Component

/**
 * 用户仓储mysql实现
 */
@Component
class UserRepositoryMysqlImpl(
    private val userMapper: UserMapper,
    private val userRoleMapper: UserRoleMapper
) : UserRepository, UserAppQueryRepository {
    /**
     * 保存用户
     */
    override fun save(userEntity: UserEntity) {
        //保存用户-聚合根
        storeUser(userEntity)
    }

    /**
     * 保存用户
     */
    private fun storeUser(userEntity: UserEntity) {
        //保存用户实体
        userMapper.storeEntity(userEntity) { it.toUserDO() }
        //处理值对象
        val roles = userEntity.roles
        userRoleMapper.saveValueObjects(toUserRoles(userEntity.id!!, roles)) {
            eq(UserRoleDO::userId, userEntity.id!!)
        }
    }


    /**
     * 通过用户名查找用户
     */
    override fun oneUserByUsername(username: String): UserEntity? {
        log.info("通过用户名查找用户：$username")
        return userMapper.queryOne {
            eq(UserDO::username, username)
        }?.toUserEntity()?.bindRoles()
    }
    /**
     * 通过用户id查找用户
     */
    override fun oneUser(userId: Long): UserEntity? {
        log.info("通过用户id查找用户：$userId")
        return userMapper.queryOne { eq(UserDO::id, userId) }?.toUserEntity()?.bindRoles()

    }
    /**
     * 通过用户id查找用户
     */
    private fun UserEntity.bindRoles(): UserEntity {
        val roleIds: List<Long> = userRoleMapper.queryList {
            eq(UserRoleDO::userId, id)
        }.map { it.roleId }
        roles = roleIds
        return this
    }
}